package com.adkun.community.util;

import com.upyun.RestManager;
import com.upyun.UpException;
import com.upyun.UpYunUtils;
import lombok.extern.slf4j.Slf4j;
import okhttp3.Response;
import org.springframework.stereotype.Component;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Component
@Slf4j
public class UpYunTools {

    private final List<RestManager> upYuns;


    public UpYunTools(List<RestManager> upYuns) {
        this.upYuns = upYuns;
    }

    /**
     * 上传头像
     *
     * @param path 又拍云的上传地址
     * @param imgInputStream 图片输入流
     * @return
     */
    public Map<String, String> uploadHeaderImg(String path, InputStream imgInputStream) {
        RestManager upYunHeader = upYuns.get(0);

        // 额外参数
        Map<String, String> params = new HashMap<>();
        // 文件类型
        params.put(RestManager.PARAMS.CONTENT_TYPE.getValue(), ".png");
        // 验证md5，如果上传服务器发现md5不正确，则拒绝
//        params.put(RestManager.PARAMS.CONTENT_MD5.getValue(), UpYunUtils.md5(imgInputStream, 1024));

        // 上传文件
        Response response = null;
        try {
            response = upYunHeader.writeFile(path, imgInputStream, params);
        } catch (IOException | UpException e) {
            log.error("上传图片失败！" + e.getMessage());
        }

        // 返回结果
        Map<String, String> result = new HashMap<>();
        // 上传是否成功
        assert response != null;
        result.put("success", response.isSuccessful() ? "true" : "false");
        // 上传到的url
        result.put("url", response.request().url().toString());
        return result;
    }

}
